<?php
/**
 * A rail_link has a link to an other rail_object.
 *
 * PHP versions 5
 *
 * Copyright (C)
 * This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
 * of ERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software
 * Fundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110, USA
 *
 * @author Bastian Schröder <bs@chemanet.de>
 * @version 2008-01-25
 * @package rail
 */
class rail_link extends rail_object {

	/**
	 * Relations which are not writeable from outside. Outside means by calling set_relation or remove_relation method.
	 * The array contains only the name of protected relation not the object associated with the relation.
	 *
	 * @var array
	 */
	protected $protected_relations = array( RAIL_LINK );


	/**
	 * Get link target rail_object or false if no objects set.
	 *
	 * @exception rail_readpermission_exception
	 * @return mixed
	 */
	public function get_link () {
		// check read permission
		if( !$this->is_readable() )
		 	throw new rail_readpermission_exception( $this, $this->rail_connector->get_user() );

		if( !isset( $this->cache[ RAIL_LINK ] ) ){
			$link_relation = $this->get_relations( RAIL_LINK );

			 // throw an exception if more then one target found
			 if( count( $link_relation ) > 1 )
			 	throw new rail_exception( $this, 'found more then one target in RAIL_LINK relation from this object.' );

			 // write rail target to cache
			 if( count( $link_relation ) > 0 )
			 	$this->cache[ RAIL_LINK ] = $link_relation[0];
			 else
			 	return false;
		}

		return $this->cache[ RAIL_LINK ];
	}


	/**
	 * Set the link target.
	 *
	 * @exception rail_writepermission_exception|rail_param_exception
	 * @param rail_object $pRailObject
	 */
	public function set_link ( $pRailObject ) {
		// check write permission
		if( !$this->is_writeable() )
		 	throw new rail_writepermission_exception( $this, $this->rail_connector->get_user() );
		// check wheater new target is a rail_object
		if( !isset($pRailObject) || !$pRailObject instanceof rail_object )
			throw new rail_param_exception( $this, 'pRailObject', $pRailObject );

		// remove all existing RAIL_LINK relations
		foreach( $this->get_relations( RAIL_LINK ) as $object )
			$this->remove_relation( $object, RAIL_LINK );

		// set new RAIL_LINK relation
		$this->set_relation( $pRailObject, RAIL_LINK );
		$this->cache[ RAIL_LINK ] = $pRailObject;
	}

} // End of rail_link
?>